﻿using System;
using Apache.NMS;

namespace Reactor.Messaging.ServiceBus.Receiving
{
    public class PointToPointChannelReceiver : ReceiverBase
    {
        private readonly IMessagingChannel _queue;

        /// <summary>
        /// Initializes a new instance of the <see cref="PointToPointChannelReceiver"/> class.
        /// </summary>
        /// <param name="nmsGateway">The JMS manager.</param>
        /// <param name="session">The session.</param>
        /// <param name="queue">The queue.</param>
        public PointToPointChannelReceiver(INmsGateway nmsGateway, ISession session, IMessagingChannel queue) : base(nmsGateway, session, queue)
        {
            if(!(queue is PointToPointChannel)) throw new InvalidOperationException("QueueReceivers can only be initialized with PointToPointChannel destinations.");
            _queue = queue;
        }

        #region Base Overrides

        /// <summary>
        /// Starts this instance.
        /// </summary>
        public override void Start()
        {
            if (IsDisposed) throw new ObjectDisposedException("PointToPointChannelReceiver");

            var queue = Session.GetQueue(_queue.DestinationName);
            Consumer = Session.CreateConsumer(queue);
            Consumer.Listener += OnMessage;

            if (Log.IsInfoEnabled) Log.InfoFormat("PointToPointChannelReceiver started. Monitoring queue: {0}", _queue.DestinationName);
            IsRunning = true;
        }

        #endregion
    }
}
